package de.tum.in.eist.poll.client.control;

import java.util.Date;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;

import de.tum.in.eist.poll.client.gui.Dashboard;
import de.tum.in.eist.poll.client.gui.DateSelectorPanel;

public class DateSelectorHandler {

	private Dashboard dashboard;
	private DateSelectorPanel selector;
	private ClickHandler handler;

	public DateSelectorHandler(Dashboard dashboard,
			DateSelectorPanel dateSelector) {
		this.dashboard = dashboard;
		this.selector = dateSelector;
		init();
	}

	private void init() {
		handler = createClickHandler();
		selector.getSelectButton().addClickHandler(handler);
		selector.addHideButtonClickHandler(handler);
	}

	public ClickHandler createClickHandler() {
		return new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
				Object obj = event.getSource();
				// Hide button
				if (obj.equals(selector.getHideButton())) {
					dashboard.remove(selector);
				}
				//Select button
				else if (obj.equals(selector.getSelectButton())) {
					Date start = selector.getDateFrom();
					Date stop = selector.getDateTo();
					
					if (start != null && stop != null) {
						// Check if date from and date to is possible / not negative
						// if not, set an error notification
						if (start.compareTo(stop) > 0) {
							selector.getErrorLabel().setText("The date to should be" +
									" at least the same day as the date from!");
						} 
						// Correct input
						else{
							dashboard.getWidgetList().selectRangeView(start, stop);
							dashboard.remove(selector);
						}
					}
					// Error notifications
					else {
						boolean first = true;
						String error = "Enter";
						// Date from
						if (start == null) {
							error += " a date from";
							first = false;
						}
						// Date to
						if (stop == null) {
							if (first) {
								error += " a date to";
							} else {
								error += " and a date to";
							}
						}
						selector.getErrorLabel().setText(error + "!");
					}
				}
			}

		};
	}

}
